package com.example.messagequeue.commom;

import java.io.*;

public class BinaryRool {
    //把一个对象序列化成一个字节数组
    public static byte[] toBytes(Object object) throws IOException {
        //这个流对象相当于一个变长的字节数组
        //就可以把object序列化的数据给逐渐的写入到byteArrayOutputStream中，在统一转化成byte[]
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()){
            try (ObjectOutputStream outputStream = new ObjectOutputStream(byteArrayOutputStream)){
                //此处的writeObject就会把该对象进行序列化，生成的二进制字节数据就会写入到ObjectOutputStream中
                //由于ObjectOutputStream又是关联到ByteArrayOutputStream，最终结果写入到ByteArrayOutputStream中
                outputStream.writeObject(object);
            }
            return byteArrayOutputStream.toByteArray();
        }
    }

    //把一个字节数组反序列化成一个对象
    public static Object fromBytes(byte[] data) throws IOException, ClassNotFoundException {
        Object object = null;
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data)){
            try (ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)){
                //此处的readObject就是从data从读取数据然后进行反序列化
                object = objectInputStream.readObject();
            }
        }
        return object;
    }

}
